package com.nokia.examplegame;

import java.util.Random;

import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

public class ObstacleSprite extends Sprite {

	public static final int WIDTH = 32;
	public static final int HEIGHT = 32;
	public boolean isFromLeft = false;
	private int yCoordinate;
	private boolean jumpedOver;
	private Random myRandom = new Random();

	public ObstacleSprite(Image image, boolean fromLeft, int displayHeight) {
		super(image, WIDTH, HEIGHT);
		this.yCoordinate = displayHeight - WIDTH - 2;
		this.isFromLeft = fromLeft;
		if (!isFromLeft) {
			setTransform(TRANS_MIRROR);
		}
		this.jumpedOver = false;
		setVisible(false);
	}

	public int update(PlayerSprite player, int gameTicks, int currentLeftBound,
			int currentRightBound) {
		int retVal = 0;

		if ((getRefPixelX() + WIDTH <= currentLeftBound)
				|| (getRefPixelX() - WIDTH >= currentRightBound)) {

			setVisible(false);
		}

		if (!isVisible()) {
			int rand = getRandomInt(100);
			if (rand == 3) {

				jumpedOver = false;
				setVisible(true);

				if (isFromLeft) {
					setRefPixelPosition(currentRightBound, yCoordinate);
					move(-1, 0);
				} else {
					setRefPixelPosition(currentLeftBound, yCoordinate);
					move(1, 0);
				}
			}
		} else {

			if (gameTicks % 5 == 0) { // slow the animation down a little
				nextFrame();
			}

			if (isFromLeft) {
				move(-3, 0);
				if ((!jumpedOver) && (getRefPixelX() < player.getRefPixelX())) {
					jumpedOver = true;
					retVal = player.increaseScoreThisJump();
				}
			} else {
				move(3, 0);
				if ((!jumpedOver)
						&& (getRefPixelX() > player.getRefPixelX()
								+ PlayerSprite.WIDTH)) {
					jumpedOver = true;
					retVal = player.increaseScoreThisJump();
				}
			}

		}
		return retVal;
	}

	public int getRandomInt(int upper) {
		int retVal = myRandom.nextInt() % upper;
		if (retVal < 0) {
			retVal += upper;
		}
		return (retVal);
	}

	public void reset() {
		setVisible(false);
	    jumpedOver = false;

	}

}